//
//  String+Regular.swift
//  8-4 正则表示
//
//  Created by cyc on 16/3/10.
//  Copyright © 2016年 cyc. All rights reserved.
//

import Foundation
extension String{
 func sinSource ()-> String{
        /*
    pattern:匹配原则
    1.: 匹配任何字符串，不包括换行
    2* : 匹配任意多数量的字符
    3 ?: 尽可能少的匹配
    4.(): 捕获（）里面内容也做为匹配结果返回
    */
    let pattern=">(.*?)<"
    // let pattern=">.*<"
    //options: NSRegularExpressionOptions.DotMatchesLineSeparators可以匹配换行
    let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
    //String: 从哪内容里面来查找
    //<#T##NSRange#> ： 要查找的字符串的范围
    // 返回结果：NSTextCheckingResult
    //查找command+shift+o
    //public var numberOfRanges: Int { get }:匹配到的范围数量
    //        @available(iOS 4.0, *)
    //        public func rangeAtIndex(idx: Int) -> NSRange根据idx获取匹配范围
    //        @available(iOS 5.0, *)
    //        public func resultByAdjustingRangesWithOffset(offset: Int) -> NSTextCheckingResult
    //
    let result = regular.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.characters.count))
    //匹配范围的数量self
    let count = result?.numberOfRanges ?? 0
   
    
    if count>1{
        //获取index=1的范围来截取0 1
        let range = result?.rangeAtIndex(1)
        //            // 匹配字符串
        let  subString = (self as NSString).substringWithRange(range!)
      
        return subString
    }else{
        return "没有匹配到来源"
       }
   }

}